package com.example.demo.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.entity.Application;
import com.example.demo.entity.Medical;
import com.example.demo.mapper.ApplicationMapper;
import com.example.demo.mapper.MedicalMapper;
import com.example.demo.service.MedicalService;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
@Transactional
public class MedicalImpl implements MedicalService {

    private final MedicalMapper medicalMapper;
    private final ApplicationMapper applicationMapper;
    @Override
    public Medical addMedicalForm(Medical medical) {
        int result = medicalMapper.insert(medical);
        if (result > 0) {
            return medical;
        } else {
            throw new RuntimeException("Failed to add medical");
        }
    }
    @Override
    public String uploadToLocal(List<MultipartFile> files, Long applicationId, String basePath){
        Application application = applicationMapper.findById(applicationId);
        if(application == null) return "报名表不存在";
        if (files.isEmpty()) {
            return "上传失败，无文件";
        }
        for (MultipartFile file : files) {
            if (!file.isEmpty()) {
                try {
                    // 创建文件保存路径
                    String fileName = file.getOriginalFilename();
                    String filePath = basePath + application.getStudent().getStudentName()+
                            "/"+application.getLicence().getLicenceType();

                    // 创建目录
                    File dir = new File(filePath);
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }

                    // 保存文件
                    byte[] bytes = file.getBytes();
                    Path path = Paths.get(filePath+"/"+fileName);
                    Files.write(path, bytes);

                    // 创建 Medical 对象并设置属性
                    Medical medical = new Medical();
                    medical.setMedicalName(fileName);
                    medical.setMedicalUrl(filePath+"/"+fileName);
                    medical.setApplicationId(applicationId);
                    medicalMapper.insert(medical);
                } catch (Exception e) {
                    return "上传失败：" + e.getMessage();
                }
            } else {
                return "上传失败，请选择文件";
            }
        }
        return "上传成功";
    }
    @Override
    public List<Resource> getDownloadUrl(Long applicationId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("application_id",applicationId);
        List<Medical> medicals = medicalMapper.selectList(queryWrapper);
        List<Resource> resources = new ArrayList<>();
        medicals.forEach(medical -> {
            // 构建文件路径
            Path filePath = Paths.get(medical.getMedicalUrl());
            // 从文件系统中加载文件
            try {
                Resource resource = new UrlResource(filePath.toUri());
                resources.add(resource);
            } catch (MalformedURLException e) {
                throw new RuntimeException(e);
            }
        });
        return resources;
    }
    @Override
    public Medical findById(Long mid) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("medical_id",mid);
        return medicalMapper.selectOne(queryWrapper);
    }

    @Override
    public List<Medical> findByApplicationId(Long aid) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("application_id",aid);
        return medicalMapper.selectList(queryWrapper);
    }

    @Override
    public List<String> getDownloadPath(Long aid){
        List <Medical> medicals = findByApplicationId(aid);
        List<String> paths = new ArrayList<>();
        medicals.forEach(m->{
            paths.add(m.getMedicalUrl());
        });
        return paths;
    }

    @Override
    public String getFilePathByApplicationId(Long applicationId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("application_id",applicationId);
        Medical m = medicalMapper.selectOne(queryWrapper);
        System.out.println(m.toString());
        return m.getMedicalUrl();
    }
}
